package de.koller.worlders.engine.util.thread;

public class ResourceLoader extends Thread {

	private boolean inUse = false;
	private boolean rdy = false;
	private final IResource resource;

	public ResourceLoader( IResource resource ) {
		this.resource = resource;
		this.setDaemon( true );
		this.start();
	}
	
	synchronized public void startResource() {
		inUse = true;
		rdy = false;
		this.notifyAll();
	}
	
	synchronized public void finishResource() {
		while( !rdy )
			try { this.wait(); } catch( InterruptedException ex ) {}
		
		inUse = false;
		return;
	}

	public boolean isInUse() {
		return inUse;
	}

	@Override
	public void run() {
		while( true ) {
			synchronized( this ) {
				while( !inUse )
					try { this.wait(); } catch( InterruptedException ex ) {}
			}
			
			resource.calculateResource();
			inUse = false;
			
			synchronized( this ) {
				rdy = true;
				this.notifyAll();
			}
		}
	}
	
	public static void main( String[] args ) {
		ResourceLoader rl = new ResourceLoader( new TestResource() );
		
		System.out.println( "resource started" );
		try { Thread.sleep( 2000 ); } catch ( InterruptedException ex ) {}
		
		rl.startResource();
		System.out.println( "do something else" );
		rl.finishResource();
		System.out.println( "resource rdy" );
		
		rl.startResource();
		System.out.println( "do something else #2" );
		rl.finishResource();
		System.out.println( "resource rdy #2" );
	}
	
	private static class TestResource implements IResource {

		@Override
		public void calculateResource() {
			try { Thread.sleep( 5000 ); } catch ( InterruptedException ex ) {}
		}
		
	}
	
}
